package com.trainoo.alert.controller;

import com.alibaba.fastjson.JSONObject;
import com.trainoo.alert.service.SendDingTalkService;
import com.trainoo.alert.service.SendEmailService;
import com.trainoo.alert.service.SendSmsService;
import com.trainoo.alert.service.SendWeChatService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@RestController
public class HttpController {
	
	private Logger logger = LoggerFactory.getLogger(HttpController.class);

	@Autowired
	private SendEmailService sendEmailService;
	@Autowired
	private SendSmsService sendSmsService;
	@Autowired
	private SendWeChatService sendWeChatService;
	@Autowired
	private SendDingTalkService sendDingTalkService;


	@RequestMapping(value = "alert", method = RequestMethod.POST)
	public ResponseEntity<Map<String, String>> sendTextSms(@RequestBody String json) {
		logger.info("收到告警请求：{}",json);
		String alertTypes = (String) JSONObject.parseObject(json).get("type");
		// 遍历告警方式，逐个调用
		for(String type: alertTypes.split(",")){
			doAlert(type, json);
		}
        return new ResponseEntity<>(HttpStatus.OK);
	}

	/**
	 * 发送告警
	 * @param type 告警类别[email\sms\wechat\dingtalk]
	 * @param data
	 */
	private void doAlert(String type, String data) {
		switch (type){
			case "email":
				sendEmailService.alert(data);
				break;
			case "sms":
				sendSmsService.alert(data);
				break;
			case "wechat":
				sendWeChatService.alert(data);
				break;
			case "dingtalk":
				sendDingTalkService.alert(data);
				break;
		}
	}
}
